What is the role of `while`-loops in computation expressions in F#?
Posted
by
MizardX
on Stack Overflow
See other posts from Stack Overflow
or by MizardX
Published on 2011-01-02T03:59:28Z
Indexed on
2011/01/02
4:54 UTC
Read the original article
Hit count: 160
If you define a While
method of the builder-object, you can use while
-loops in your computation expressions. The signature of the While
method is:
member b.While (predicate:unit->bool, body:M<'a>) : M<'a>
For comparison, the signature of the For
method is:
member b.For (items:seq<'a>, body:unit->M<'a>) : M<'a>
You should notice that, in the While
-method, the body is a simple type, and not a function as in the For
method.
You can embed some other statements, like let
and function-calls inside your computation-expressions, but those can impossibly execute in a while
-loop more than once.
builder {
while foo() do
printfn "step"
yield bar()
}
Why is the while
-loop not executed more than once, but merely repeated? Why the significant difference from for-loops? Better yet, is there some intended strategy for using while-loops in computation-expressions?
© Stack Overflow or respective owner